from pydantic import BaseModel, Field, field_validator, model_validator
from typing import Optional, List, Dict, Any
from datetime import datetime, date, time
from enum import Enum
import re


class ApprovalStatus(str, Enum):
    """审核状态枚举."""
    APPROVED = "approved"
    REJECTED = "rejected"
    PENDING = "pending"


class ClassroomRequest(BaseModel):
    """教室借用申请模型（基于用户实际提供的信息）."""
    
    # 教室信息
    classroom_name: str = Field(..., description="申请的教室名称", max_length=100)
    description: str = Field(..., description="申请概述/简短描述", max_length=500)
    
    # 教师信息
    teacher_name: str = Field(..., description="任课教师姓名", max_length=50)
    teacher_email: str = Field(..., description="任课教师邮箱", max_length=100)
    
    # 用户基本信息
    applicant_name: str = Field(..., description="申请人姓名", min_length=1, max_length=50)
    user_category: str = Field(..., description="用户类别", max_length=50)
    
    # 借用类型和类别
    borrow_type: str = Field(..., description="借用类型 (例如：本科教学、研究教学、班级活动、社团活动、涉外活动、其他活动)", max_length=50)
    borrow_category: str = Field(..., description="借用类别 (例如：上课、讲座、考试、开会、自习、实习、培训、活动、其他)", max_length=50)
    
    # 设备需求
    need_equipment: bool = Field(..., description="是否申请设备")
    equipment_description: Optional[str] = Field(default=None, description="设备需求描述", max_length=500)
    
    # 房间信息
    room_info: str = Field(..., description="房间基本信息描述", max_length=1000)
    
    # 申请相关信息
    application_description: str = Field(..., description="申请说明", max_length=1000)
    application_materials: Optional[str] = Field(default=None, description="申请材料描述", max_length=1000)
    
    # 时间信息
    time_description: str = Field(..., description="申请时间描述", max_length=500)


class ClassroomResponse(BaseModel):
    """教室借用审核结果模型."""
    
    request_id: str = Field(..., description="申请ID")
    status: ApprovalStatus = Field(..., description="审核状态")
    approval_reason: str = Field(..., description="审核原因/备注", max_length=1000)
    reviewer_name: Optional[str] = Field(default="AI系统", description="审核人")
    review_timestamp: datetime = Field(default_factory=datetime.now, description="审核时间")
    
    # 审核详情
    approval_score: float = Field(..., description="审核评分", ge=0, le=100)
    risk_factors: Optional[List[str]] = Field(default=None, description="风险因素")
    recommendations: Optional[List[str]] = Field(default=None, description="建议")
    
    # 条件审批
    conditions: Optional[List[str]] = Field(default=None, description="审批条件")
    
    class Config:
        json_encoders = {
            datetime: lambda v: v.isoformat(),
            date: lambda v: v.isoformat(),
            time: lambda v: v.strftime('%H:%M:%S')
        }


class ApprovalRules(BaseModel):
    """审核规则模型."""
    
    rules_text: str = Field(..., description="审核规则文本", min_length=10)
    strict_mode: bool = Field(default=False, description="是否启用严格模式")
    auto_approve_threshold: float = Field(default=80.0, description="自动通过阈值", ge=0, le=100)
    auto_reject_threshold: float = Field(default=30.0, description="自动拒绝阈值", ge=0, le=100)
    
    @field_validator('auto_reject_threshold')
    @classmethod
    def validate_thresholds(cls, v, info):
        if info.data and 'auto_approve_threshold' in info.data and v >= info.data['auto_approve_threshold']:
            raise ValueError('自动拒绝阈值必须小于自动通过阈值')
        return v